﻿using BusinessLayer.Biz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Biz
{
    public class Cart
    {
        private List<CartItem> cart;
        private Unsold unsold = new Unsold();
        public Cart()
        {
            cart=new List<CartItem>();
        }

        public bool AddToCart(Product product, int quantity)
        {

            if (IsProductExistInCart(product))
            {
                return IncreaseQuantity(product, quantity);

            }
            else
            {
                var newItem = new CartItem { Product = product, Count = quantity,CurrentPrice=product.CurrentPrice};//tam thoi xai price sau nay se tinh lai gia
                cart.Add(newItem);
                //if (unsold.GetQuantityByProduct(product) < quantity)
                //{
                //    re
                //}
            }
            return true;
        }
        public void RemoveFromCart(int id)
        {
            var cartItem = cart.First(c => c.Product.Id == id);
            cart.Remove(cartItem);
        }
        public bool IncreaseQuantity(Product product, int quantity)
        {
            var cartItem = cart.First(c => c.Product.Id == product.Id);
            cartItem.Count += quantity;
            if (cartItem.Count > unsold.GetQuantityByProduct(product))
            {
                cartItem.Count -= quantity;
                return false;
            }
            return true;
        }
        public bool UpdateQuantity(Product product, int quantity)
        {
            var cartItem = cart.First(c => c.Product.Id == product.Id);
            if (quantity > unsold.GetQuantityByProduct(product))
            {
                return false;
            }
            cartItem.Count = quantity;
            return true;
        }
        public bool IsProductExistInCart(Product product)
        {
            return cart.Any(c => c.Product.Id == product.Id);
        }
        public int GetCount()
        {
            return cart.Count();
        }
        public decimal GetTotal()
        {
            decimal Total = (from cartItems in cart
                             select (decimal)(cartItems.Count * cartItems.CurrentPrice)).Sum();
            return Total;
        }
        public IEnumerable<CartItem> ListItem
        {
            get { return cart; }
        }

    }
}